package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.eventbus.UserInfoChangeEvent;
import com.blockmeta.bbs.immodule.net.api.DeleteFriendApi;
import com.blockmeta.bbs.immodule.net.api.ShieldUserApi;
import com.blockmeta.bbs.immodule.widget.IMAddFriendMsg;
import com.suke.widget.SwitchButton;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author airthor
 * @date 2019/2/20
 * 好友设置界面 设置备注屏蔽消息
 */
public class FriendsSettingActivity extends BaseActivity implements SwitchButton.OnCheckedChangeListener {
    @BindView(R2.id.tv_friend_remarks)
    TextView mTvFriendRemarks;
    @BindView(R2.id.cl_share_to_friend)
    ConstraintLayout mClShareToFriend;
    @BindView(R2.id.iv_message_ignore)
    SwitchButton mIvMessageIgnore;
    @BindView(R2.id.btn_add_friend)
    Button mBtnAddFriend;
    @BindView(R2.id.btn_delete_friend)
    Button mBtnDeleteFriend;
    @BindView(R2.id.cl_remarks)
    ConstraintLayout mcl_remarks;

    private IMAddFriendMsg imPopAddFriendMsg;
    private boolean isFriend;

    private long mFriendId;
    private String mName, mAvatar, mDesc;
    private boolean mIsShield;

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_friends_setting, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        setTitleText("个人设置");
        mFriendId = getIntent().getLongExtra(Params.USERID, 0);
        isFriend = IMApplicationContext.getUserDomainService().isFriend(mFriendId);
        mIsShield = getIntent().getBooleanExtra(Params.ISSHIELD, false);
        mName = getIntent().getStringExtra(Params.USER_NAME);
        mAvatar = getIntent().getStringExtra(Params.USER_AVATAR);
        mDesc = getIntent().getStringExtra(Params.USER_DESC);

        mClShareToFriend.setVisibility(isFriend ? View.VISIBLE : View.GONE);
        mBtnAddFriend.setVisibility(isFriend ? View.GONE : View.VISIBLE);
        mBtnDeleteFriend.setVisibility(isFriend ? View.VISIBLE : View.GONE);
        mcl_remarks.setVisibility(isFriend ? View.VISIBLE : View.GONE);

        network();
    }

    private void network() {
        setShieldSwitch(mIsShield);
    }

    private void setShieldSwitch(boolean isShield) {
        mIvMessageIgnore.setOnCheckedChangeListener(null);
        mIvMessageIgnore.setChecked(isShield);
        mIvMessageIgnore.setOnCheckedChangeListener(FriendsSettingActivity.this);
    }

    @OnClick({R2.id.cl_remarks, R2.id.cl_share_to_friend, R2.id.cl_message_ignore, R2.id.btn_add_friend, R2.id.btn_delete_friend})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.cl_remarks) {
            Intent remarkIntent = new Intent(mContext, RemarksActivity.class);
            remarkIntent.putExtra(Params.USERID, mFriendId);
            startActivity(remarkIntent);

        } else if (i == R.id.cl_share_to_friend) {
            Intent personalQRIntent = new Intent(mContext, PersonalQrCodeActivity.class);
            personalQRIntent.putExtra(Params.USERID, mFriendId);
            personalQRIntent.putExtra(Params.USER_NAME, mName);
            personalQRIntent.putExtra(Params.USER_AVATAR, mAvatar);
            personalQRIntent.putExtra(Params.USER_DESC, mDesc);
            startActivity(personalQRIntent);
        } else if (i == R.id.btn_add_friend) {
            addFriend(mFriendId + "");

        } else if (i == R.id.btn_delete_friend) {
            deleteFriend(mFriendId);

        } else {
        }
    }


    /**
     * 添加好友
     *
     * @param friendId 要添加的好友ID
     */
    private void addFriend(String friendId) {
        imPopAddFriendMsg = new IMAddFriendMsg(mContext, friendId + "");
        imPopAddFriendMsg.show();
    }

    /**
     * 删除好友
     *
     * @param friendId 要删除的好友ID
     */
    private void deleteFriend(final long friendId) {
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRetrofit().create(DeleteFriendApi.class)
                .deleteFriend(AccountHelper.getUidInt(), friendId)
                .compose(RxUtil.dataNullResult())
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(((RxAppCompatActivity) mContext).<BaseImResponse<Object>>bindToLifecycle())
                .subscribe(new CommonSubscriber<BaseImResponse<Object>>(mContext) {
                    @Override
                    public void onNext(BaseImResponse<Object> o) {
                        ToastUtil.show("删除好友成功");
                        IMApplicationContext.getUserDomainService().deleteFriend(friendId);
                        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_DeleteFriends());
                        finish();

                    }
                });
    }

    private void shieldUser(final long toId, final boolean isChecked) {
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRootRetrofit().create(ShieldUserApi.class)
                .shieldUser(toId, isChecked)
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(RxUtil.dataNullResult())
                .compose(((RxAppCompatActivity) mContext).<BaseImResponse<Object>>bindToLifecycle())
                .subscribe(new CommonSubscriber<BaseImResponse<Object>>(mContext) {
                    @Override
                    public void onNext(BaseImResponse<Object> o) {
//                            ToastUtil.show("成功");
                        mIsShield = isChecked;
                        Map<String, String> notifyMap = new HashMap<>(1);
                        notifyMap.put("shield", String.valueOf(mIsShield));
                        IMApplicationContext.getIMMetaService().post(new UserInfoChangeEvent(toId, notifyMap));
                        mIvMessageIgnore.setEnabled(true);

                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        ToastUtil.show("失败");
                        setShieldSwitch(!isChecked);
                        mIvMessageIgnore.setEnabled(true);
                    }
                });
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        view.setEnabled(false);
        shieldUser(mFriendId, isChecked);
    }
}
